;
(function() {
    var getConfTimer = null;
    var isReady = false;
    var _this = share = {
        /**
         * 去掉两端空格
         */
        trim: function(str) {
            if (!str) {
                return;
            }
            return str.replace(/(^\s*)|(\s*$)/g, '');
        },
        /**
         * 获取移动端浏览器版本
         */
        isPC: function() {
            return !navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
        },
        getBrowser: function() {
            var ua = navigator.userAgent;

            if (ua.indexOf('Weibo') > -1) {
                return 'Weibo';
            }

            if (ua.indexOf('Firefox') > -1 || ua.indexOf('FxiOS') > -1) {
                return 'Firefox';
            }

            if (ua.indexOf('Opera') > -1) {
                return 'Opera';
            }

            if (ua.indexOf('UCBrowser') > -1) {
                return 'UCBrowser';
            }

            if (ua.indexOf('MicroMessenger') > -1) {
                return 'MicroMessenger'; // 微信内置浏览器
            }

            if (ua.indexOf('MQQBrowser') > -1) {
                return 'MQQBrowser'; // QQ浏览器
            }

            if (ua.match(/QQ/i) == 'QQ') {
                return 'QQ'; // QQ内置浏览器
            }

            if (ua.indexOf('Chrome') > -1 || ua.indexOf('CriOS') > -1) {
                return 'Chrome';
            }

            if (ua.indexOf('Safari') > -1) {
                return 'Safari';
            }

            return '';
        },
        /**
         * 获取微信配置信息
         */
        getWeixinShareConfig: function() {
            ajax.getWeixinShareConfig({
                url: window.location.href.split("#")[0],
                success_cb: function(res) {
                    var data = res.data;
                    if (!window.wx) {
                        return;
                    }
                    wx.config({
                        debug: false,
                        appId: data.appId,
                        timestamp: data.timestamp,
                        nonceStr: data.nonceStr,
                        signature: data.signature,
                        jsApiList: data.jsApiList
                    })
                    _this.setDefaultShareInfo();
                    wx.ready(function() {
                        isReady = true;
                    });
                },
                fail_cb: function(err) {
                    console.error(err);
                }
            })
        },
        /**
         * 设置微信配置信息
         */
        setDefaultShareInfo: function() {
            var count = 0;
            getConfTimer = setInterval(function() {
                count++;
                if (count > 20 || isReady) {
                    clearInterval(getConfTimer);
                    shareData = _this.getShareData();
                    var opts = {
                        title: shareData.title, // 分享标题
                        desc: shareData.desc, // 分享描述
                        link: shareData.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: shareData.imgUrl, // 分享图标
                        success: function() {

                        },
                        fail: function(err) {
                            console.error('分享失败，请稍后重试');
                        }
                    }
                    wx.updateAppMessageShareData(opts);
                    wx.updateTimelineShareData(opts);
                }
            }, 500);
        },
        /**
         * 微信分享
         */
        weixinShare: function(shareData) {
            if (!shareData) {
                return;
            }
            var opts = {
                title: shareData.title, // 分享标题
                desc: shareData.desc, // 分享描述
                link: shareData.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: shareData.imgUrl, // 分享图标
                success: function() {

                },
                fail: function(err) {
                    alert('分享失败，请稍后重试');
                }
            }
            wx.updateAppMessageShareData(opts);
            wx.updateTimelineShareData(opts);
        },
        /**
         * 处理分享数据
         * @param {boolean} isWorkShare 是否是学生作品弹窗分享
         */
        getShareData: function(isWorkShare) {
            if (!window.util) {
                return;
            }
            var shareData = {
                title: '', // 分享标题
                desc: '2020中央美术学院研究生毕业展', // 分享描述
                link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: '', // 分享的图片
                source: '' // 分享来源
            };
            var url = window.location.href;
            var guid = util.getQueryString('guid');
            if (url.indexOf('vtour.html') > -1) {
                if (guid && guid === 'f5230284-2d61-8114-82b5-20d45d5f7369') {
                    shareData.title = '2020中央美院研究生线上毕业展';
                } else {
                    var collegeName = $('#collegeNav').find('.cm-btn.on').text();
                    shareData.title = '2020央美' + (collegeName ? collegeName : '') + '研究生线上毕业展';
                }
                shareData.imgUrl = 'http://art2020.cafa.edu.cn/school_us/img/logo-share.jpg';
            }

            if (url.indexOf('/cloud/') > -1 || url.indexOf('/cloud/m/index') > -1 || url.indexOf('/cloud/index') > -1) {
                shareData.title = '2020央美' + $('#collegeInfo h2').text() + '研究生线上毕业展';
                shareData.imgUrl = $('#collegeInfo img').attr('src');
            }

            if (url.indexOf('/cloud/m/list') > -1) {
                shareData.title = '2020央美' + $('#workListNav a.on').text() + '研究生线上毕业展';
                shareData.imgUrl = $('#preface img').attr('src');
            }

            if (url.indexOf('/cloud/list') > -1) {
                shareData.title = '2020央美' + $('#collegeHeaderList a.on').text() + '研究生线上毕业展';
                shareData.imgUrl = $('.preface img').attr('src');
            }

            if (isWorkShare) { // 学生作品分享
                var college = $('#departmentName dd').html().split('|');
                var collegeName = _this.trim(college[0]);
                var departmentName = college[1] ? _this.trim(college[1]) : '';
                var student = $('#student dd').html().split('|');
                var studentName = _this.trim(student[0]);
                var studentNo = _this.trim(student[1]);
                shareData.title = '中央美院' + collegeName + departmentName + studentName + '毕业作品';
                var sourceFrom = '';
                if (url.indexOf('vtour') > -1 || url.indexOf('design/') > -1) {
                    sourceFrom = '3d';
                } else {
                    sourceFrom = '2d';
                }
                shareData.link = 'https://art2020.cafa.edu.cn/student/info?student_no=' + studentNo + '&source_from=' + sourceFrom;


                shareData.imgUrl = $('#workModal').attr('data-thumb');
            }
            return shareData;
        },
        /**
         * 打开通用分享弹层
         */
        openCommonShareMenu: function() {
            layer.open({
                type: 1,
                content: $('#shareBox').html(),
                anim: 'up',
                style: 'position:fixed; bottom:0; left:0; width: 100%; padding:10px 0; border:none;'
            });
        },
        /**
         * 处理不同平台分享
         */
        handleShare: function(shareData) {
            var browser = _this.getBrowser();

            if (!shareData) {
                return;
            }

            if (browser == 'MicroMessenger') { // 微信内置浏览器
                _this.weixinShare(shareData);
                $('#shareGuide').show();
            } else {
                if (window.mqq && browser == 'QQ') { // QQ内置浏览器分享
                    mqq.data.setShareInfo({
                        title: shareData.title,
                        source: shareData.source,
                        desc: shareData.desc,
                        image_url: shareData.imgUrl,
                        share_url: shareData.link
                    });
                    mqq.ui.showShareMenu();
                    mqq.ui.setOnShareHandler(function(type) {
                        mqq.ui.shareMessage({
                            title: shareData.title,
                            desc: shareData.desc,
                            share_type: type,
                            share_url: shareData.link,
                            image_url: shareData.imgUrl,
                            source: shareData.source,
                            back: true
                        }, function(ret) {
                            if (ret.retCode === 0) {

                            } else {

                            }
                        });
                    });
                } else
                if (browser == 'UCBrowser') { // UC分享
                    var isiOS = /(iPhone|iPad|iPod)/.test(navigator.userAgent); // 判断应用平台
                    if (isiOS) {
                        if (!window.ucbrowser) {
                            return false;
                        }
                        if (ucbrowser.web_shareEX) {
                            ucbrowser.web_shareEX(
                                JSON.stringify({
                                    title: shareData.title,
                                    content: shareData.desc,
                                    sourceUrl: shareData.link,
                                    imageUrl: shareData.imgUrl,
                                    source: shareData.source
                                })
                            )
                        } else {
                            ucbrowser.web_share(shareData.title, shareData.desc, shareData.link, [], '', shareData.source, shareData.imgUrl);
                        }
                    } else {
                        if (window.ucweb) {
                            ucweb.startRequest('shell.page_share', [shareData.title, shareData.desc, shareData.link, [], '', shareData.source, shareData.imgUrl]);
                        }
                    }
                } else {
                    _this.openCommonShareMenu();
                    // 	点击微博
                    $('#weibo').live('click', function() {
                        layer.closeAll();
                        location.replace('https://service.weibo.com/share/share.php?url=' + encodeURIComponent(shareData.link) + '&title=' + shareData.title + '&pic=' + shareData.imgUrl);
                    })

                    // 点击QQ
                    $('#qqFriend').live('click', function() {
                        layer.closeAll();
                        var url_scheme = '//share/to_fri?src_type=web&version=1&file_type=news&title=' + Base64.encode(shareData.title) + '&thirdAppDisplayName=' + Base64.encode(shareData.source) + '&url=' + Base64.encode(shareData.link) + '&description=' + Base64.encode(shareData.desc);
                        location.assign('mqqapi:' + url_scheme);
                        setTimeout(function() {
                            location.assign('timapi:' + url_scheme);
                        }, 2000);
                    });


                    // 点击QQ空间
                    $('#qqZone').live('click', function() {
                        layer.closeAll();
                        location.replace('https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + encodeURIComponent(shareData.link) + '&site=中央美术学院研究生线上毕业展&title=' + shareData.title + '&pics=' + shareData.imgUrl + '&summary=' + shareData.desc);
                    });


                    // 点击微信
                    $('#weChat').live('click', function() {
                        layer.closeAll();
                        Clipboard.copy(shareData.link);
                        _this.toast('地址复制成功！请到微信中复制分享～');
                    });
                }
            }
        },

        /**
         * 提示弹窗
         * @param {string} msg 提示消息
         * @param {integer} time 弹窗显示时间
         */
        toast: function(msg, time) {
            var timer = null;
            $('#toast .tip').text(msg);
            $('#toast').show();
            if (typeof time == 'undefined') {
                time = 2;
            }
            clearTimeout(timer);
            timer = setTimeout(function() {
                $('#toast').hide();
                clearTimeout(timer);
            }, time * 1000);
        },
        hanldePCShareInit: function() {

            if (!$('#workModal').is(":hidden")) {
                shareData = _this.getShareData(true);
            } else {
                shareData = _this.getShareData();
            }
            var $config = {
                title: shareData.title || document.title,
                description: shareData.desc,
                url: shareData.link,
                source: shareData.link,
                image: shareData.imgUrl,
                summary: shareData.desc, //相当于description
                // sites   : ['qzone', 'qq', 'weibo','wechat', 'douban'], // 启用的站点
                disabled: ['google', 'facebook', 'twitter', 'linyin'], // 禁用的站点
                wechatQrcodeTitle: "微信扫一扫：分享", // 微信二维码提示文字
                // wechatQrcodeHelper: '立即下载发送专属二维码,邀请朋友加入',
            };
            socialShare('.social-share', $config);
            setTimeout(function() {
                _this.openCommonShareMenu();
            }, 0)


        },
        /**
         * 分享初始化
         */
        initShare: function() {
            $('#shareGuide').live('click', function() {
                $(this).hide();
            });

            if (_this.isPC()) {
                $('.btn-share').live('click', function(e) {
                    e.stopPropagation();
                    var shareBox = $(".share-box").clone()
                    shareBox.find(".social-share-icon").attr("href", "javascript:;").empty()
                    $(".share-box").remove()
                    $("body").append(shareBox)
                    _this.hanldePCShareInit();

                });
            } else {
                var browser = _this.getBrowser()
                if (browser == 'MicroMessenger') {
                    _this.getWeixinShareConfig();
                }
                if (browser == 'Weibo' || browser == 'QQ') {
                    $('#qqFriend').hide();
                }
                $('.btn-share').live('click', function(e) {
                    e.stopPropagation();
                    var shareData = null;
                    clearInterval(getConfTimer);
                    if ($(this).closest('#workModal').length) {
                        shareData = _this.getShareData(true);
                    } else {
                        shareData = _this.getShareData();
                    }
                    _this.handleShare(shareData);
                });
            }

        },
        /**
         * 初始化
         */
        init: function() {
            _this.initShare();
        }
    }
    _this.init();
})();